/**
 * Created by Administrator on 2016/5/14.
 */
/**
 * 页面加载完毕后发送AJAX获取当前存在的城市信息
 */
$(document).ready(function () {
    $.ajax({
        type: 'GET',
        url: '/cities',
        success: function (data) {
            appendToList(data);
        }
    });
});

/**
 * 将数据添加到列表中
 *
 * @param data
 */
function appendToList(data) {
    if (isArray(data)) {
        var list = [];
        for (var i = 0; i < data.length; i++) {
            var content = "<img class='deleteCity' src='../images/delete.png' data-name='" + data[i] + "'/>"
                + "<a href='/cities/"+data[i]+"'>" + data[i] + "</a>";
            list.push($('<li>', {html: content}));
        }
        $('#cities').append(list);
        $(".deleteCity").on('click', deleteCity);
    }
}

/**
 * 判断一个对象是不是数组
 *
 * @param data
 */
function isArray(data) {
    return "[object Array]" === Object.prototype.toString.call(data);
}

/**
 * 当表单提交时
 */
$("form").on('submit', function (event) {
    event.preventDefault();
    var form = $("form");

    $.ajax({
        type: 'POST',
        url: '/cities',
        data: form.serialize()
    }).done(function (data) {
        appendToList([data]);
        form.trigger('reset');
    }).error(function () {
        alert('信息不能为空！');
    });
});

/**
 * 当点击删除图标时
 */
function deleteCity (event) {
    var target = $(event.currentTarget);
    var cityName = target.data('name');
    if(confirm("你确实要删除"+cityName+"吗?")) {
        $.ajax({
            type: 'DELETE',
            url: '/cities/'+cityName
        }).done(function () {
            target.parents('li').remove();
        });
    }
}
